package com.zjsru.plan2023.oneday.oneDay202302;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: CookLee
 * @Date: 2023/2/8
 * 删除子文件夹
 *
 * 输入：folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"]
 * 输出：["/a","/c/d","/c/f"]
 * 解释："/a/b" 是 "/a" 的子文件夹，而 "/c/d/e" 是 "/c/d" 的子文件夹。
 *
 * 输入：folder = ["/a","/a/b/c","/a/b/d"]
 * 输出：["/a"]
 * 解释：文件夹 "/a/b/c" 和 "/a/b/d" 都会被删除，因为它们都是 "/a" 的子文件夹。
 */
public class RemoveSubfolders {
    
    /**
     * 删除子文件夹:模拟
     *
     * @param folder 文件夹
     * @return {@link List}<{@link String}>
     */
    public List<String> removeSubfolders(String[] folder) {
        //按照字母大小排序
        Arrays.sort(folder);
        List<String> ans = new ArrayList<>();
        String first = folder[0];
        ans.add(first);
        for (int i = 1; i < folder.length; i++) {
            int pre = ans.get(ans.size() - 1).length();
            //子文件夹长度一定大于文件夹
            //比较sub截取的前缀是不是文件夹
            //比较有没有”/" ，如果有说明文件后面还有路径
            if (!(pre < folder[i].length() && ans.get(ans.size() - 1).equals(folder[i].substring(0, pre)) &&
                    folder[i].charAt(pre) == '/')) {
                ans.add(folder[i]);
            }
        }
        return ans;
    }
    
    public static void main(String[] args) {
        RemoveSubfolders removeSubfolders = new RemoveSubfolders();
        String[] folder = new String[]{"/a","/a/b","/c/d","/c/d/e","/c/f"};
        System.out.println(removeSubfolders.removeSubfolders(folder));
    }
}
